const fs = require('fs');
const { resolve, extname } = require('path');

// extname  后缀名字
const dirToJson = (url) => {
  //1. 判断是文件还是目录
  if (fs.statSync(url).isFile()) { //是文件
    return {
      name: url,
      path: resolve(url),
      type: extname(url).slice(1) // js html css png
    }
  } else { //是目录
    return {
      name: url,
      path: resolve(url),
      type: '文件夹',
      children: fs.readdirSync(url).map((item) => { //递归调用
        return dirToJson(url + '/' + item);
      })
    }
  }
}

let res = dirToJson('./src');
fs.writeFileSync('data.json', JSON.stringify(res));